package com.qiao.glod.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.qiao.glod.R;
import com.qiao.glod.api.GoldApi;
import com.qiao.glod.bean.GiftBean;
import com.qiao.glod.bean.ImageWarper;
import com.qiao.glod.bean.Results;
import com.qiao.glod.util.NetUtils;

import org.byteam.superadapter.SuperAdapter;
import org.byteam.superadapter.internal.SuperViewHolder;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Qiao on 2016/4/7.
 * function：
 */
public class ContentFragment3 extends QFragment implements SwipeRefreshLayout.OnRefreshListener{
    SwipeRefreshLayout swipeRefreshLayout;
    SuperAdapter<GiftBean> mAdapter;
    String type ;
    int page=1;

    @Override
    protected int generateResId() {
        return R.layout.fragment_main;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getArguments().getString("type");
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        swipeRefreshLayout = findView(R.id.swipe);
        swipeRefreshLayout.setOnRefreshListener(this);

        bindRecyclerView();

    }

    private void bindRecyclerView(){
        RecyclerView recyclerView = findView(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setHasFixedSize(true);

        recyclerView.setAdapter(mAdapter = new SuperAdapter<GiftBean>(getContext(),
                loadData(),
                R.layout.gifts_item_layout){
            @Override
            public void onBind(SuperViewHolder holder, int viewType, int position, GiftBean item) {
                holder.setText(R.id.txt_gifts_title,item.getDesc());
                holder.setText(R.id.gifts_author,item.getWho());
                Glide.with(getContext())
                        .load(item.getImg())
                        .into((ImageView) holder.getView(R.id.img_gifts_img));
            }
        });
    }

    private List<GiftBean> loadData(){
        List<GiftBean> data = GiftBean.getGitfs(type,GoldApi.LOAD_LIMIT,page);
        if(data==null || data.size()==0){
            //判断有没有网络
            if (NetUtils.isNetWorkConection(context)) {
                //进来就自动刷新
                swipeRefreshLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(true);
                        onRefresh();
                    }
                });
            }
        }
        return data;
    }

    @Override
    public void onRefresh() {
        GoldApi.getGankApi().getGifts(GoldApi.LOAD_LIMIT,page)
                .enqueue(new Callback<Results>() {
                    @Override
                    public void onResponse(Call<Results> call, Response<Results> response) {
                        if(response.isSuccessful()){
                            results = response.body();
                            Log.i("getGiftsByType---"+type,"onResponse：" + results.toString());
                            wrapData();
                        }
                    }

                    @Override
                    public void onFailure(Call<Results> call, Throwable t) {
                        Log.e("Error:getGiftsByType---"+type,"Message：" + t.getMessage());
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });

        GoldApi.getMeituApi().getImageList(GoldApi.LOAD_LIMIT,page)
                .enqueue(new Callback<ImageWarper>() {
                    @Override
                    public void onResponse(Call<ImageWarper> call, Response<ImageWarper> response) {
                        if(response.isSuccessful()){
                            warper = response.body();
                            Log.i("getImageList---"+type,"onResponse：" + response.toString());
                            wrapData();
                        }
                    }

                    @Override
                    public void onFailure(Call<ImageWarper> call, Throwable t) {
                        Log.e("Error:getImageList---"+type,"Message：" + t.getMessage());
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    private Results results;
    private ImageWarper warper;
    private void wrapData(){
        if(results==null || warper==null) return;//数据未加载完成

        if(results.isError() || !warper.isStatus() ) {
            swipeRefreshLayout.setRefreshing(false);
            return;
        }

        int i = 0;
        for(GiftBean bean:results.getResults()){
            bean.setImg(warper.getTngou().get(i++).getImg());
            bean.save();
        }

        if(page==1)
            mAdapter.addAll(results.getResults());
        else
            mAdapter.replaceAll(results.getResults());

        results = null;
        warper = null;
        swipeRefreshLayout.setRefreshing(false);
    }

}
